package com.android.djlmapp.activity.my;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.constraint.ConstraintLayout;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.djlmapp.R;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.base.BaseActivity;
import com.android.djlmapp.dialog.MyUsualyDialog;
import com.android.djlmapp.http.GlobalUrls;
import com.android.djlmapp.token.TokenExpiredUtils;
import com.android.djlmapp.tools.global.GlobalContants;
import com.android.djlmapp.tools.global.MD5Util;
import com.android.djlmapp.tools.global.ToastUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


public class YzCodeActivity extends BaseActivity {
    public static final String TAG = "djlm-my: ";

    @BindView(R.id.tv_bdsjh)
    TextView tvBdsjh;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.ed_phone)
    EditText edPhone;
    @BindView(R.id.ed_yzm)
    EditText edYzm;
    @BindView(R.id.tv_hqyzm)
    TextView tvHqyzm;
    @BindView(R.id.tv_change)
    TextView tvChange;
    @BindView(R.id.activity_change_phone_num)
    LinearLayout activityChangePhoneNum;
    @BindView(R.id.ll_top_back)
    LinearLayout llTopBack;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.home_iv_readpoint)
    ImageView homeIvReadpoint;
    @BindView(R.id.top_notes)
    ImageView topNotes;
    @BindView(R.id.iv_top_msg)
    ConstraintLayout ivTopMsg;
    @BindView(R.id.iv_top_set)
    ImageView ivTopSet;
    @BindView(R.id.iv_top_kf)
    ImageView ivTopKf;
    @BindView(R.id.page_title_layout)
    ConstraintLayout pageTitleLayout;

    private Unbinder mUnbinder;
    private MyUsualyDialog dialog;
    private String pNum;
    private String type = "1";
    MyCountDownTimer myCountDownTimer;
    private String yzm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yz_code);
        mUnbinder = ButterKnife.bind(this);

        initView();
        initData();
        // 加载进度条
        dialog = new MyUsualyDialog(YzCodeActivity.this, R.layout.wait_item);
        dialog.setCanceledOnTouchOutside(false);
        pNum = getIntent().getStringExtra("pNum");

    }

    @Override
    protected void initView() {
        homeIvReadpoint.setVisibility(View.GONE);
        topNotes.setVisibility(View.GONE);
    }

    @Override
    protected void initData() {
//        initWindow(rl_title);
        //new倒计时对象,总共的时间,每隔多少秒更新一次时间
        myCountDownTimer = new MyCountDownTimer(60000, 1000);
        tvName.setText("更换手机号");
        tvChange.setText("验证验证码");
        tvBdsjh.setText("旧手机号");

        tvPhone.setVisibility(View.VISIBLE);
        edPhone.setVisibility(View.GONE);

        edYzm.setInputType(InputType.TYPE_CLASS_NUMBER);

    }

    @Override
    protected void onResume() {
        super.onResume();
        // 代码顺序一致，会出现加载不出来字符串（需要放在此处）
        tvPhone.setText(pNum);
    }

    @OnClick({R.id.ll_top_back, R.id.tv_hqyzm, R.id.tv_change, R.id.activity_change_phone_num})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_top_back:
                finish();
                break;
            case R.id.tv_hqyzm:
                // 获取验证码
                // 开启定时器
                myCountDownTimer.start();
                getCodeNet();
                break;
            case R.id.tv_change:
                //  验证验证码
                dialog.show();
                tvChange.setText("验证中");
                tvChange.setEnabled(false);
                yzm = edYzm.getText().toString().trim();
                yzCodeNet();
                break;
            case R.id.activity_change_phone_num:
                break;
        }
    }

    //复写倒计时
    private class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        //计时过程
        @Override
        public void onTick(long l) {
            //防止计时过程中重复点击
            tvHqyzm.setClickable(false);
            tvHqyzm.setText(l / 1000 + "s后重新获取");

        }

        //计时完毕的方法
        @Override
        public void onFinish() {
            //重新给Button设置文字
            tvHqyzm.setText("重新获取验证码");
            //设置可点击
            tvHqyzm.setClickable(true);
        }
    }

    private void getCodeNet() {

        MyApplication.getInstance().getHttpTools().getCode(pNum, type, new StringCallback() {
            @Override
            public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                try{
                    parseJson(response.body(), 1);
                }catch(Exception e){
                    tvHqyzm.setText("重新获取验证码");
                    tvHqyzm.setEnabled(true);
                    ToastUtils.showShortToast(YzCodeActivity.this, "数据解析异常"+e.toString());
                }
            }

            @Override
            public void onError(com.lzy.okgo.model.Response<String> response) {
                super.onError(response);
                Toast.makeText(YzCodeActivity.this,
                        "请检查您的网络", Toast.LENGTH_SHORT).show();
                tvHqyzm.setText("重新获取验证码");
                tvHqyzm.setEnabled(true);
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }

    class YzmInfo {
        public String code;
        public String msg;
    }

    private void parseJson(String s, final int index) {
        Gson gson = new Gson();
        YzmInfo yzmInfo = gson.fromJson(s, YzmInfo.class);
        Log.i(TAG, "yanzhengma: " + s);

        if (yzmInfo != null) {
            int count = Integer.parseInt(yzmInfo.code);
            if (count < 1000) {
                if (index == 2) {
                    Toast.makeText(YzCodeActivity.this,
                            "验证成功", Toast.LENGTH_SHORT).show();
                    // 验证成功后跳转绑定手机页
                    startActivity(new Intent(YzCodeActivity.this, ChangePhoneNumActivity.class));
                    finish();
                }
            }  else {
                Toast.makeText(YzCodeActivity.this,
                        yzmInfo.msg, Toast.LENGTH_SHORT).show();
            }
        }
    }


    private void yzCodeNet() {
        MyApplication.getInstance().getHttpTools().checkCode(pNum, yzm, new StringCallback() {
            @Override
            public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                tvChange.setText("验证验证码");
                tvChange.setEnabled(true);
                dialog.dismiss();
                try{
                    parseJson(response.body(), 2);
                }catch(Exception e){
                    ToastUtils.showShortToast(YzCodeActivity.this, "数据解析异常"+e.toString());
                }
            }

            @Override
            public void onError(com.lzy.okgo.model.Response<String> response) {
                super.onError(response);
                tvChange.setText("验证验证码");
                tvChange.setEnabled(true);
                dialog.dismiss();
                Toast.makeText(YzCodeActivity.this,
                        "请检查您的网络", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUnbinder.unbind();
    }
}
